package com.web.quartz.service.impl;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import org.elasticsearch.client.Request;
import org.elasticsearch.client.RestClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import com.web.common.basic.entity.ElasticsearchIndex;
import com.web.common.basic.quartz.entity.QuartzJobOperateLog;
import com.web.common.basic.quartz.entity.QuartzJobOperateLogEntity;
import com.web.common.result.R;
import com.web.common.result.ResultEnum;
import com.web.common.tool.DateTimeUtil;
import com.web.common.tool.Symbols;
import com.web.service.handler.error.CustomException;
import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch._types.SortOptions;
import co.elastic.clients.elasticsearch._types.SortOrder;
import co.elastic.clients.elasticsearch._types.query_dsl.Query;
import co.elastic.clients.elasticsearch.core.SearchRequest;
import co.elastic.clients.elasticsearch.core.SearchResponse;
import co.elastic.clients.elasticsearch.core.search.Hit;
import co.elastic.clients.json.JsonData;

@Service
public class QuartzOperateLogServiceImpl {

	private ObjectMapper mapper = new ObjectMapper();

	@Autowired
	private RestClient elRestClient;

	@Autowired
	private ElasticsearchClient elasticsearchClient;
	
	public R<Object> saveOperateLog(QuartzJobOperateLog log) {
		R<Object> json = new R<>();
		LocalDateTime dateTime = LocalDateTime.now();
		log.setOperateTime(dateTime.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME));
		
		try {
			JavaTimeModule module = new JavaTimeModule();
			module.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(DateTimeFormatter.ISO_DATE_TIME));
			mapper.registerModule(module);

			String body = mapper.writeValueAsString(log);

			UUID uuid = UUID.randomUUID();
			Request request = new Request("POST",
					Symbols.FORWARD_SLASH + ElasticsearchIndex.QUARTZ_OPERATE_LOG_INDEX + "/_doc/" + uuid.toString());
			request.setJsonEntity(body);
			elRestClient.performRequest(request);
		} catch (Exception e) {
			e.printStackTrace();
		}
		json.setResultEnum(ResultEnum.SUCCESS);
		return json;
	}
	
	/**
	 * 获取定时任务的日志信息列表
	 * @param condition 查询条件
	 * @return IPage<QuartzJobOperateLog> 分页数据列表
	 *
	 * @author zhouhui
	 * @since 2023.11.02 
	 */
	public R<IPage<QuartzJobOperateLog>> getOperateLogList(QuartzJobOperateLogEntity condition){
		R<IPage<QuartzJobOperateLog>> json = new R<>();
		
		setSearchCondition(condition);
		
		SearchResponse<QuartzJobOperateLog> result = null;
		try {
			List<Query> queryList = setLogQueryList(condition);
			SortOptions sort = SortOptions.of(fn -> fn.field(f -> f.field("operateTime").order(SortOrder.Desc)));	
			
			SearchRequest request = SearchRequest
					.of(fn -> fn.index(ElasticsearchIndex.QUARTZ_OPERATE_LOG_INDEX)
					.query(q -> q.bool(b -> b.must(queryList)))
					.sort(sort)
					.from((condition.getPage() - 1) * condition.getSize())
					.size(condition.getSize()));
			result = elasticsearchClient.search(request, QuartzJobOperateLog.class);
		} catch (Exception e) {
			e.printStackTrace();
		}
		if(result == null) {
			throw new CustomException(ResultEnum.DATA_QUERY_ERROR.getMessage());
		}
		List<Hit<QuartzJobOperateLog>> hits = result.hits().hits();
		List<QuartzJobOperateLog> logList = new ArrayList<>(hits.size());
		for(Hit<QuartzJobOperateLog> item: hits) {
			QuartzJobOperateLog source = item.source();
			if(StringUtils.hasText(source.getOperateTime())) {
				source.setOperateTime(dateTimeConvert(source.getOperateTime()));
			}
			logList.add(item.source());
		}
		IPage<QuartzJobOperateLog> page = new Page<>(condition.getPage(), condition.getSize());
		page.setTotal(result.hits().total().value());
		page.setRecords(logList);
		page.setCurrent(condition.getPage());
		page.setSize(condition.getSize());
		json.setData(page);
		json.setResultEnum(ResultEnum.SUCCESS);
		return json;
	}
	
	/**
	 * 时间转换
	 * @param dateTime 时间的字符串
	 * @return 固定格式的时间字符串
	 *
	 * @author zhouhui
	 * @since 2023.11.02 
	 */
	private String dateTimeConvert(String dateTime) {
		LocalDateTime tempDateTime = LocalDateTime.parse(dateTime, DateTimeFormatter.ISO_LOCAL_DATE_TIME);
		return tempDateTime.format(DateTimeFormatter.ofPattern(DateTimeUtil.YEAR_MONTH_DATE_TIME));
	}
	
	/**
	 * 设置查询条件
	 * @param condition 查询信息
	 *
	 * @author zhouhui
	 * @since 2023.08.19
	 */
	private void setSearchCondition(QuartzJobOperateLogEntity condition) {
		if(condition.getStartDateTime() == null || condition.getEndDateTime() == null) {
			throw new CustomException("未选择时间范围");
		}
		if(condition.getEndDateTime().isBefore(condition.getStartDateTime())) {
			throw new CustomException("开始时间不能大于结束时间");
		}
		int year = condition.getStartDateTime().getYear() - condition.getEndDateTime().getYear();
		if(year > 1) {
			throw new CustomException("查询数据范围不能超过一年");
		}
	}
	
	/**
	 * 设置日志的查询条件列表
	 * @param condition 查询条件
	 * @return List<Query> 查询条件列表
	 *
	 * @author zhouhui
	 * @since 2023.08.19
	 */
	private List<Query> setLogQueryList(QuartzJobOperateLogEntity condition) {
		String startDateTime = condition.getStartDateTime().format(DateTimeFormatter.ISO_LOCAL_DATE_TIME);
		String endDateTime = condition.getEndDateTime().format(DateTimeFormatter.ISO_LOCAL_DATE_TIME);
		
		List<Query> queryList = new ArrayList<>();
		Query dateQuery = Query.of(q -> q.range(range -> range.field("operateTime").gte(JsonData.of(startDateTime)).lte(JsonData.of(endDateTime))));
		queryList.add(dateQuery);
		if(StringUtils.hasText(condition.getJobName())) {
			Query userCodeQuery = Query.of(q -> q.match(m -> m.field("jobName").query(condition.getJobName())));
			queryList.add(userCodeQuery);
		}
		return queryList;
	}
}
